﻿using Plugins;
using Plugins.Base.Common;
using Plugins.UserControls;

namespace MomentumPlugin.Common
{
	internal class OnFixedAmountProcessor : IDecisionEngineExitProcessor
	{
		#region Attributes

		private readonly HourSelectorData _hourSettings;
		private readonly DecisionEngineData _data;
		private readonly OperationManager _operationManager;
		private readonly StrategyControlData _strategySettings;

		#endregion

		#region Public Methods

		public OnFixedAmountProcessor(HourSelectorData hourSettings, DecisionEngineData data, OperationManager operationManager, StrategyControlData strategySettings)
		{
			_hourSettings = hourSettings;
			_data = data;
			_operationManager = operationManager;
			_strategySettings = strategySettings;
		}

		public DecisionEngineStateBase ProcessOnLongPossition()
		{
			DecisionEngineState result = null;
			int currentVolume = _data.LastQuotation.Buyers[0].Quantity;
			decimal startPrice = _operationManager.CurrentOperation.BuyPrice;
			decimal currentPrice = _data.LastQuotation.Buyers[0].Value;

			if (_data.LastQuotation.Date.TimeOfDay >= _hourSettings.ForcedCloseTime || currentPrice >= startPrice + _strategySettings.MinWin || currentPrice <= startPrice  - _strategySettings.MaxLoss && currentVolume >= _strategySettings.Volume)
			{
				_data.Values.Clear();
				_data.Values.Add(_data.PreviousQuotation.Value);
				_operationManager.CloseLongPossition();

				result = DecisionEngineState.CountingDown;
			}

			return result;
		}

		public DecisionEngineStateBase ProcessOnShortPossition()
		{
			DecisionEngineState result = null;
			int currentVolume = _data.LastQuotation.Buyers[0].Quantity;
			decimal startPrice = _operationManager.CurrentOperation.SellPrice;
			decimal currentPrice = _data.LastQuotation.Sellers[0].Value ;

			if (_data.LastQuotation.Date.TimeOfDay >= _hourSettings.ForcedCloseTime || currentPrice <= startPrice - _strategySettings.MinWin || currentPrice >= startPrice + _strategySettings.MaxLoss && currentVolume >= _strategySettings.Volume)
			{
				_data.Values.Clear();
				_data.Values.Add(_data.PreviousQuotation.Value);
				_operationManager.CloseShortPossition();

				result = DecisionEngineState.CountingUp;
			}

			return result;
		}

		#endregion
	}
}
